package cn.com.lms.business.examRewrite.web;

import cn.com.lms.business.examRewrite.persistence.entity.QuestionReWriteVo;
import cn.com.lms.business.examRewrite.service.QuestionCategoryReWriteService;
import cn.com.lms.business.examRewrite.service.QuestionReWriteService;
import com.bnzj.core.persistence.query.CompareExpression;
import com.bnzj.core.persistence.query.CompareType;
import com.bnzj.core.persistence.query.IExpression;
import com.bnzj.core.persistence.query.QueryHelpBean;
import com.bnzj.core.rest.ResponseResult;
import com.bnzj.core.webmvc.util.WebMvcUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/exam/question")
public class QuestionReWriteController {

    @Autowired
    QuestionReWriteService questionReWriteService;

    @Autowired
    QuestionCategoryReWriteService questionCategoryReWriteService;

    /**
     * 获取题库的列表
     * @param request
     */
    @GetMapping("/pageReWrite")
    public ResponseResult<Page<QuestionReWriteVo>> getQuestionPage(HttpServletRequest request){
        String keyWord = request.getParameter("keyWord");
        String categoryId = request.getParameter("CategoryId");

        // 设置sql
        QueryHelpBean queryHelpBean = QuestionReWriteService.getQueryHelpBean();
        // 分页条件
        Pageable pageable = WebMvcUtils.initPage(request, Sort.by(Sort.Direction.DESC, "eq.create_time"));
        queryHelpBean.setPageable(pageable);
        // eq.is_delete 为false
        IExpression build = CompareExpression.build("eq.is_delete", CompareType.equal, false);
        queryHelpBean.addWhere(build);

        // 判断条件是否为空
        if (!StringUtils.isEmpty(keyWord)){
            IExpression iExpression = CompareExpression.build("eq.question_name", CompareType.like, keyWord);
            queryHelpBean.addWhere(iExpression);
        }

        // 判断树
        if (!StringUtils.isEmpty(categoryId) && !categoryId.equals(0)) {
            // 树
            List<Long> ChildrenIds = questionCategoryReWriteService.findChildrenIds(Long.valueOf(categoryId));
            ChildrenIds.add(Long.valueOf(categoryId));
            IExpression build1 =  CompareExpression.build("eq.category_id", CompareType.in, ChildrenIds);
            queryHelpBean.addWhere(build1);
        }

        Page<QuestionReWriteVo> all = questionReWriteService.findAll(queryHelpBean);
        return ResponseResult.success(all);

    }
}
